<?php

declare(strict_types=1);

/**
 * 文件 utils
 *
 * @version      0.0.1
 * @author      by huwhois
 * @time        20228/10
 */

namespace app\utils;

use think\Image;
use think\Exception;
use think\File;
use think\image\Exception as ImageException;
use think\facade\Config;
use think\file\UploadedFile;

class FileUtils
{
    /**
     * 图片添加水印
     * @param File $file  要处理的文件
     * @param int $type  水印类型 0 图片水印, 1 文字水印 
     * @param string $waterimg  图片水印内容
     * @param string $watertext  文字水印内容
     * @param string $fonttype  水印文字类型
     * @param int $fontsize  水印文字大小
     * @param string $fontcolor  水印文字颜色
     * @return Image  返回图片对象
     */
    public function waterMark(
        Image $image,
        int $type = 0,
        string $watermark = '',
        string $watertext = '',
        string $fonttype = '',
        int $fontsize = 0,
        string $fontcolor = '#ffffff30'
    ): Image {
        if ($type == 0) {
            $watermark = $watermark ?: Config::get('filesystem.water.watermark');
            $image->water($watermark);
        } else {
            $watetext = $watertext ?: Config::get('filesystem.water.watertext');
            $fonttype = $fonttype ?: Config::get('filesystem.water.fonttype');
            $fontsize = $fontsize ?: (int) Config::get('filesystem.water.fontsize');
            $fontcolor = $fontcolor ?: (int) Config::get('filesystem.water.fontcolor');

            $image->text($watetext, $fonttype, $fontsize, $fontcolor);
        }

        return $image;
    }

    /**
     * 生成缩略图
     * @param Image $image  要处理的文件
     * @param int $width 缩略图宽值, 默认 384px;
     * @param int $height 缩略图高值, 默认 224px;
     * @param int $type 缩略图裁剪方式, 默认值 1,固定尺寸缩放; 其他: 1,等比例缩放;2,缩放后填充;3,居中裁剪;4,左上角裁剪;5,右下角裁剪
     * @param string $t_suffix  缩略图后缀
     * @return Image  返回图片对象
     */
    public function thumbnail(Image $image, string $thumbname, int $width = 384, int $height = 224, int $type = 1)
    {
        $image->thumb($width, $height, $type)->save('./storage/' . $thumbname);

        return $image;
    }

    /**
     * 保存远程图片到本地
     */
    public static function downloadUrlImg(string $url)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0); // 只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);

        curl_close($ch);

        // halt($httpinfo);
        $imageAll = array_merge(array(
            'imgBody' => $package
        ), $httpinfo);
        if ($httpinfo['download_content_length'] > 4 * 1024 * 1024) {
            throw new Exception("文件太大", 1);
        }

        $type = null;

        $originalName = "";

        switch ($imageAll['content_type']) {
            case 'image/gif':
                $type = "gif";
                break;
            case 'image/webp':
                $type = "webp";
                break;
            case 'image/jpeg':
                $type = "jpg";
                break;
            case 'image/png':
                $type = "png";
                break;
            default:
                $type = null;
                break;
        }

        // 腾讯公众号图片
        if (strpos($url, 'qpic.cn') !== false) {
            $urls = parse_url($url);

            if (isset($urls['query'])) {
                $query_arr = [];

                parse_str($urls['query'], $query_arr);

                $type = isset($query_arr['wx_fmt']) ? $query_arr['wx_fmt'] : null;

                $type = $type == 'jpeg' ? 'jpg' : $type;
            }
        }

        if (!$type) {
            throw new Exception("不支持的文件后缀", 1);
        }

        $originalName = pathinfo($url, PATHINFO_EXTENSION) ? basename($url) : basename($url) . '.' . $type;

        $temp =  app()->getRuntimePath() . 'temp';

        if (!file_exists($temp)) {
            mkdir($temp, 0755);
        }
        
        $tempname = $temp . DIRECTORY_SEPARATOR . 'php' . substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 6) . '.tmp';

        file_put_contents($tempname, $imageAll["imgBody"]);

        return new UploadedFile($tempname, $originalName, $imageAll["content_type"]);
    }

    /**
     * 遍历获取目录下的指定类型的文件
     * @param $path
     * @param $allowFiles  png|jpg|jpeg|gif|bmp|webp
     * @param array $files
     * @return array
     */
    public static function getFiles($path, $allowFiles = 'png|jpg|jpeg|gif|bmp|webp', &$files = array())
    {
        if (!is_dir($path)) return null;
        if (substr($path, strlen($path) - 1) != '/') $path .= '/';
        $handle = opendir($path);
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..') {
                $path2 = $path . $file;
                if (is_dir($path2)) {
                    self::getFiles($path2, $allowFiles, $files);
                } else {
                    if (preg_match("/\.(" . $allowFiles . ")$/i", $file)) {
                        $files[] = array(
                            'url' => substr($path2, strlen(app()->getRootPath() . '/public') - 1),
                            'mtime' => filemtime($path2)
                        );
                    }
                }
            }
        }
        return $files;
    }
}
